package kz.kstu.scantest.desktop.report;

import kz.kstu.scantest.business.common.helper.FormDataHelper;
import kz.kstu.scantest.business.common.util.comparator.FormDataComparator;
import kz.kstu.scantest.business.entity.data.FormData;
import kz.kstu.scantest.business.entity.data.dto.FormDataDTO;
import kz.kstu.scantest.business.entity.guide.School;
import kz.kstu.scantest.business.util.StringUtil;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import java.awt.*;
import java.io.InputStream;
import java.util.*;
import java.util.List;

/**
 * @author Filipp_Stankevich
 *         created: 20.09.11 19:38
 */
public class AnswerFormDataReport extends AbstractFormDataReport {

    private final static String REPORT_FILE = "reports/answersReport.jrxml";

    @Override
    public JasperPrint buildReport(List<FormData> formDataList) throws JRException {
        ClassLoader classLoader = AbstractFormDataReport.class.getClassLoader();
        InputStream report = classLoader.getResourceAsStream(REPORT_FILE);
        JasperReport jasperReport = JasperCompileManager.compileReport(report);
        Map<String, Object> parameters = new HashMap<String, Object>();
        List<FormDataDTO> formDataDTOList = new ArrayList<FormDataDTO>();
        if (formDataList != null && formDataList.size() > 0) {
            Comparator<FormData> comparator =  new FormDataComparator(StringUtil.getGetterByProperty(FormData.SURNAME_PROPERTY));
            Collections.sort(formDataList, comparator);
            int rowNumber = 1;
            for (FormData formData : formDataList) {
                FormDataDTO formDataDTO = FormDataHelper.convertToDTO(formData);
                formDataDTO.setRowNumber(rowNumber++);
                formDataDTOList.add(formDataDTO);
            }
            School school = formDataList.get(0).getSchool();
            parameters.put("school", school);
        }
        Image logoImage = getLogoImage();
        parameters.put("logo", logoImage);
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(formDataDTOList);
        return JasperFillManager.fillReport(jasperReport, parameters, dataSource);
    }
}
